package com.dingwei.superiordiary.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.adapter.adapter.MyOrderListAdapter;
import com.dingwei.superiordiary.bean.OrderListBean;
import com.dingwei.superiordiary.bean.OrderPayBean;
import com.dingwei.superiordiary.mvp.presenter.MyOrderPresenter;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.utils.Constants;
import com.dingwei.superiordiary.utils.DialogUtil;
import com.dingwei.superiordiary.utils.PayResult;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.easyrecyclerview.decoration.DividerDecoration;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.utils.AppManager;
import com.lihao.baselibrary.utils.DisplayUtil;
import com.lihao.baselibrary.utils.L;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lihao on 2018/1/11.
 */

public class MyOrderActivity extends BaseActivity implements Contract.MyOrderView {

    MyOrderPresenter myOrderPresenter = new MyOrderPresenter(this);
    @Bind(R.id.img_back)
    ImageView imgBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.m_recyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.no_data_layout)
    RelativeLayout noDataLayout;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.no_net_btn)
    TextView noNetBtn;
    @Bind(R.id.no_net_layout)
    RelativeLayout noNetLayout;
    @Bind(R.id.order_tablayout)
    TabLayout orderTablayout;


    private String status = "0";
    private MyOrderListAdapter adapter;
    private int page = 1;
    IWXAPI api;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_my_order;
    }

    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        myOrderPresenter.initData(page, true, true,status);
    }

    @Override
    protected void initData() {
        refreshLayout.autoRefresh();
    }

    protected void initView() {

        initTab();


        tvTitle.setText("我买到的");

        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.addItemDecoration(new DividerDecoration(getResources().getColor(R.color.bg1), DisplayUtil.dip2px(BaseActivity.context, 8)));
        adapter = new MyOrderListAdapter(this);
        mRecyclerView.setAdapter(adapter);
    }

    private void initTab() {




        orderTablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                status = tab.getPosition()+"";

                page = 1;
                myOrderPresenter.initData(page, true, true,status);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        orderTablayout.addTab(orderTablayout.newTab().setText("全部"));
        orderTablayout.addTab(orderTablayout.newTab().setText("待支付"));
        orderTablayout.addTab(orderTablayout.newTab().setText("待发货"));
        orderTablayout.addTab(orderTablayout.newTab().setText("待收货"));
        orderTablayout.addTab(orderTablayout.newTab().setText("已完成"));
        orderTablayout.addTab(orderTablayout.newTab().setText("售后"));
    }


    @Override
    protected void initListener() {
        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page = page + 1;
                myOrderPresenter.initData(page, false, true,status);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                myOrderPresenter.initData(page, true, true,status);
            }
        });

        adapter.setMyInterfaceListener(new MyOrderListAdapter.myInterFace() {
            @Override
            public void leftClick(final int position) {
                final OrderListBean.DataBean data = adapter.getItem(position);
                switch (data.status) {
                    case 1://取消订单
                        DialogUtil.showAlertDialogChoose(BaseActivity.context, "温馨提示", "是否确认取消订单", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case DialogUtil.BUTTON1:
                                        dialog.dismiss();
                                        break;
                                    case DialogUtil.BUTTON2://确认
                                        dialog.dismiss();
                                        myOrderPresenter.deleteOrder(data.id, position);
                                        break;
                                }
                            }
                        });
                        break;
                    case 2:
                        if (data.service_status == 1) {
                            //填写退款信息
                            intent = new Intent(BaseActivity.context, ReturnGoodsActivity.class);
                            intent.putExtra("id", data.id);
                            intent.putExtra("type","1");
                            intent.putExtra("title", "退款");
                            intent.putExtra("price", data.amount + "");
                            startActivity(intent);
                        } else {
                            //查询退款进度
                            intent = new Intent(BaseActivity.context, WaitAuditActivity.class);
                            intent.putExtra("id", data.id);
                            startActivity(intent);
                        }

                        break;
                    case 3:
                        //查询物流
                        intent = new Intent(BaseActivity.context, LogisticsLogActivity.class);
                        intent.putExtra("id", data.id);
                        startActivity(intent);
                        break;
                    case 4:
                        if (data.service_status == 2 || data.service_status == 3 || data.service_status == 5 || data.service_status == 6 || data.service_status == 7) {
                            //查询退款进度
                            intent = new Intent(BaseActivity.context, WaitAuditActivity.class);
                            intent.putExtra("id", data.id);
                            startActivity(intent);
                        } else if (data.service_status == 4) {
                            //填写物流单号
                            intent = new Intent(BaseActivity.context, FillInLogisticsNumberActivity.class);
                            intent.putExtra("id", data.id);
                            startActivity(intent);
                        } else {
                            //填写退货信息
                            intent = new Intent(BaseActivity.context, ReturnGoodsActivity.class);
                            intent.putExtra("id", data.id);
                            intent.putExtra("type","1");
                            intent.putExtra("price", data.amount + "");
                            intent.putExtra("title", "退货退款");
                            startActivity(intent);
                        }
                        break;
                    case 5:
                        if (data.service_status == 7) {
                            //查询退款进度
                            intent = new Intent(BaseActivity.context, WaitAuditActivity.class);
                            intent.putExtra("id", data.id);
                            startActivity(intent);
                        }
                        break;
                }
            }

            @Override
            public void rightClick(final int position) {
                final OrderListBean.DataBean data = adapter.getItem(position);
                switch (data.status) {
                    case 1:
                        //去付款
                        DialogUtil.showPayDialog(BaseActivity.context, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case DialogUtil.WXPAYBUTTON1:
                                        dialog.dismiss();
                                        myOrderPresenter.payOrder(data.id, "wx");
                                        break;
                                    case DialogUtil.AlipayBUTTON2:
                                        dialog.dismiss();
                                        myOrderPresenter.payOrder(data.id, "alipay");
                                        break;
                                }
                            }
                        });
                        break;
                    case 2:
                        DialogUtil.showAlertDialogChoose(BaseActivity.context, "温馨提示", "是否确认删除订单", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case DialogUtil.BUTTON1:
                                        dialog.dismiss();
                                        break;
                                    case DialogUtil.BUTTON2://确认
                                        dialog.dismiss();
                                        myOrderPresenter.deleteOrder(data.id, position);
                                        break;
                                }
                            }
                        });
                        break;
                    case 3:
                        //确认收货
                        DialogUtil.showAlertDialogChoose(BaseActivity.context, "温馨提示", "是否确认收货", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case DialogUtil.BUTTON1:
                                        dialog.dismiss();
                                        break;
                                    case DialogUtil.BUTTON2://确认
                                        dialog.dismiss();

                                        myOrderPresenter.orderConfrm(data.id, position);
                                        break;
                                }
                            }
                        });
                        break;
                    case 4:
                    case 5:
                        DialogUtil.showAlertDialogChoose(BaseActivity.context, "温馨提示", "是否确认删除订单", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case DialogUtil.BUTTON1:
                                        dialog.dismiss();
                                        break;
                                    case DialogUtil.BUTTON2://确认
                                        dialog.dismiss();
                                        myOrderPresenter.deleteOrder(data.id, position);
                                        break;
                                }
                            }
                        });
                        break;
                }
            }

            @Override
            public void OneClick(int position) {
                final OrderListBean.DataBean data = adapter.getItem(position);
                if (data.service_status == 12 || data.service_status == 13 || data.service_status == 15 || data.service_status == 16 || data.service_status == 17) {
                    //查询退款进度
                    intent = new Intent(BaseActivity.context, WaitAuditActivity.class);
                    intent.putExtra("id", data.id);
                    startActivity(intent);
                } else if (data.service_status == 14) {
                    //填写物流单号
                    intent = new Intent(BaseActivity.context, FillInLogisticsNumberActivity.class);
                    intent.putExtra("id", data.id);
                    startActivity(intent);
                } else {
                    //填写退货信息
                    intent = new Intent(BaseActivity.context, ExchangeGoodsActivity.class);
                    intent.putExtra("id", data.id);
                    intent.putExtra("type","2");
                    intent.putExtra("price", data.amount + "");
                    intent.putExtra("title", "换货");
                    startActivity(intent);
                }
            }

            @Override
            public void goods(int position) {
                final OrderListBean.DataBean data = adapter.getItem(position);
                intent = new Intent(BaseActivity.context, CommodityDetailsActivity.class);
                intent.putExtra("id", data.product_id);
                startActivity(intent);
            }
        });

    }

    @OnClick({R.id.img_back, R.id.no_net_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.no_net_btn:
                page = 1;
                myOrderPresenter.initData(page, true, true,status);
                break;
        }
    }


    public void showData(String state) {
        if (state.equals("success")) {
            refreshLayout.setVisibility(View.VISIBLE);
            noNetLayout.setVisibility(View.GONE);
            if (adapter.getAllData() == null || adapter.getAllData().size() == 0) {
                noDataLayout.setVisibility(View.VISIBLE);
                mRecyclerView.setVisibility(View.GONE);
            } else {
                mRecyclerView.setVisibility(View.VISIBLE);
                noDataLayout.setVisibility(View.GONE);
            }
        } else {
            refreshLayout.setVisibility(View.GONE);
            noNetLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onRefresh(OrderListBean bean) {
        adapter.clear();
        adapter.addAll(bean.data);
        refreshLayout.finishRefresh();
        showData("success");
    }

    @Override
    public void onLoadMore(OrderListBean bean) {
        adapter.addAll(bean.data);
        refreshLayout.finishLoadmore();
        showData("success");
    }

    @Override
    public void onFail() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        showData("fail");
    }

    @Override
    public void orderConfirmSuccess(int position) {
//        adapter.getItem(position).status = 4;
//        adapter.notifyItemChanged(position);
        page = 1;
        myOrderPresenter.initData(page, true, true,status);
    }

    @Override
    public void deleteOrderSuccess(int position) {
        adapter.remove(position);
        showData("success");
    }

    @Override
    public void wxPay(OrderPayBean bean) {
        api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID);
        api.registerApp(Constants.WX_APP_ID);
        registorPayBroadCast();

        PayReq req = new PayReq();
        req.appId = Constants.WX_APP_ID;
        req.partnerId = bean.data.wx.partnerid;
        req.prepayId = bean.data.wx.prepayid;
        req.packageValue = "Sign=WXPay";
        req.nonceStr = bean.data.wx.noncestr;
        req.timeStamp = bean.data.wx.timestamp + "";
        req.sign = bean.data.wx.paysign;

        boolean s = api.sendReq(req);
        L.e("s---->" + s);
        if (!s) {
            showToast("未安装微信，无法支付");
        }
    }

    private void registorPayBroadCast() {
        if (mPayBroadCastRecevier != null) {
            unregisterReceiver(mPayBroadCastRecevier);
        }
        // 生成广播处理
        mPayBroadCastRecevier = new PayBroadCastRecevier();
        // 实例化过滤器并设置要过滤的广播
        IntentFilter intentFilter = new IntentFilter(Constants.ACTION_PAY_RESULT);
        // 注册广播
        context.registerReceiver(mPayBroadCastRecevier, intentFilter);
    }

    PayBroadCastRecevier mPayBroadCastRecevier;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    class PayBroadCastRecevier extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            final int code = intent.getIntExtra("code", BaseResp.ErrCode.ERR_COMM);
            switch (code) {
                case BaseResp.ErrCode.ERR_OK:
                    L.e("支付成功");
                    AppManager.getAppManager().finishActivity(EditOrderActivity.class);
                    AppManager.getAppManager().finishActivity();
                    refreshLayout.autoRefresh();
                    break;
                case BaseResp.ErrCode.ERR_COMM:
                    showToast("支付失败");
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    showToast("取消支付");
                    break;

            }
        }
    }


    @Override
    public void alipay(final OrderPayBean bean) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(MyOrderActivity.this);
                Map<String, String> result = alipay.payV2(bean.data.zfb, true);

                Message msg = new Message();
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    /**
     * 支付宝支付回调
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            L.e("支付宝返回的信息---->" + resultInfo + "" + payResult.getResultStatus() + "---" + payResult.getMemo());
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                Toast.makeText(MyOrderActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                AppManager.getAppManager().finishActivity(EditOrderActivity.class);
                AppManager.getAppManager().finishActivity();
                refreshLayout.autoRefresh();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                Toast.makeText(MyOrderActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

}
